package com.example.glideprogressiveloadimg

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.RadioGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.DrawableImageViewTarget
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.ImageViewTargetFactory
import com.bumptech.glide.request.transition.Transition
import com.example.glideprogressiveloadimg.util.anim.FadeInImageDisplayer
import com.example.glideprogressiveloadimg.util.anim.SimpleImageDisplayer

class MainActivity : AppCompatActivity() {
    val TAG = MainActivity::class.java.simpleName

    val url1 = "http://118.24.17.191/images/ppp.jpg"
    val url2 = "http://118.24.17.191/images/ppp4.jpg"
    val url3 =
        "http://lazada-processed-image.oss-ap-southeast-1.aliyuncs.com/aaron-burden-183659.jpg?x-oss-process=image/format,jpg/interlace,1"

    val url4 = "http://www.reasoft.com/tutorials/web/img/progress.jpg";

    val url5 = "http://www.webkaka.com/blog/archives/demo/1_normal-4276_50k.jpg"  //普通jpg
    val url6 =
        "http://lazada-processed-image.oss-ap-southeast-1.aliyuncs.com/aaron-burden-183659.jpg" //普通jpg

    var url = url1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val iv: ImageView = findViewById(R.id.iv)
        val tvAddress: TextView = findViewById(R.id.tv_address)
        val tv: TextView = findViewById(R.id.tv_progress)
        val tvInfo: TextView = findViewById(R.id.tv_info)
        val btn_load: Button = findViewById(R.id.btn_load)
        val rg: RadioGroup = findViewById<RadioGroup>(R.id.rg)
        rg.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb1 -> {
                    url = url1
                    tvAddress.text = url
                }
                R.id.rb2 -> {
                    url = url2
                    tvAddress.text = url
                }
                R.id.rb3 -> {
                    url = url3
                    tvAddress.text = url
                }
                R.id.rb4 -> {
                    url = url4
                    tvAddress.text = url
                }
                R.id.rb5 -> {
                    url = url5
                    tvAddress.text = url
                }
                R.id.rb6 -> {
                    url = url6
                    tvAddress.text = url
                }
            }
        }
        rg.check(R.id.rb1)
        tvAddress.text = url

        btn_load.setOnClickListener {
            loadWithListener(applicationContext, url, iv, object : ProgressListener {
                private var firstLoadFrameIndex: Int = 0
                private var loadFrameIndex: Int = 0
                private var loadCount: Int = 0
                private var isFirstLoad = false
                override fun onLoadProgress(
                    isDone: Boolean,
                    progress: Int,
                    bitmap: Bitmap?,
                    frameIndex: Int) {
                    Log.d(TAG, "isDone = $isDone, progress= $progress, bitmap = $bitmap, frameIndex = $frameIndex")
                    bitmap?.let {
                        iv.post {
                            if (!isFirstLoad) {
                                FadeInImageDisplayer(500).display(it, iv)
                                isFirstLoad = true
                            }else {
                                SimpleImageDisplayer().display(it, iv)
                            }

                            Log.d(TAG, "progressive load bitmap to imageView, frameIndex = $frameIndex, progress = $progress,  bitmap =$bitmap")
                            loadFrameIndex = frameIndex
                            if (firstLoadFrameIndex == 0) {
                                firstLoadFrameIndex = frameIndex
                            }
                            loadCount++
                        }
                    }
                    tv.post {
                        tv.text = "图片下载进度$progress%"
                    }

                    tvInfo.post {
                        val info = StringBuffer()
                        info.append("当前帧:$frameIndex, 加载帧: $loadFrameIndex, 初始加载帧:$firstLoadFrameIndex, 加载次数: $loadCount")
                        tvInfo.text = info.toString()
                    }
                }

                override fun onLoadFailed() {
                    Log.d(TAG, "onLoadFailed :: ")
                }
            })
        }
    }

    var target : DrawableImageViewTarget?=null
    fun loadWithListener(context: Context, url: String, imageView: ImageView, listener: ProgressListener) {
        ProgressInterceptor.addListener(url, listener)

        target = object : DrawableImageViewTarget(imageView) {
            override fun onLoadStarted(placeholder: Drawable?) {
                super.onLoadStarted(placeholder)
//                imageView.setImageResource(R.color.color_646464)
                Log.d(TAG, "progressive load bitmap to imageView started")
            }

            override fun onLoadFailed(errorDrawable: Drawable?) {
                super.onLoadFailed(errorDrawable)
                ProgressInterceptor.LISTENER_MAP.get(url)?.onLoadFailed()
                imageView.setImageResource(R.color.color_transparent)
            }

            override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                super.onResourceReady(resource, transition)
                ProgressInterceptor.removeListener(url)
                Log.d(TAG, "progressive load bitmap to imageView done")
            }
        }

        val whiteColor = ContextCompat.getColor(applicationContext, R.color.white)
        GlideApp.with(applicationContext)
            .load(url)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .placeholder(ColorDrawable(whiteColor))
            .skipMemoryCache(true)!!.into(target!!)
    }
}
